import axios from 'axios';
// import Global from './global';
import constant from './constant';

const log = function () {
  const args = [...arguments];
  const info = args.map((item, index) => {
    return index ? `%c${JSON.stringify(item)}` : `%c${item}: => `;
  }).join(' ');
  const colorKey = {
    request: 'lightGreen',
    response: 'lightBlue',
    error: 'red'
  }
  const color = colorKey[args[0].match(/[\s]\w+$/g)[0].replace(' ', '')];
  console.info(info, `background: black; color: ${color};`, 'background: linear-gradient(to left, rgba(252,234,187,1) 0%, rgba(175,250,77,1) 12%, rgba(0,247,49,1) 28%, rgba(0,210,247,1) 39%,rgba(0,189,247,1) 51%, rgba(133,108,217,1) 64%, rgba(177,0,247,1) 78%, rgba(247,0,189,1) 87%, rgba(245,22,52,1) 100%);background: -webkit-gradient(left top, right top, color-stop(0%, rgba(252,234,187,1)), color-stop(12%, rgba(175,250,77,1)), color-stop(28%, rgba(0,247,49,1)), color-stop(39%, rgba(0,210,247,1)), color-stop(51%, rgba(0,189,247,1)), color-stop(64%, rgba(133,108,217,1)), color-stop(78%, rgba(177,0,247,1)), color-stop(87%, rgba(247,0,189,1)), color-stop(100%, rgba(245,22,52,1)))');
}

class Request {
  constructor (options = {
    timeout: 11000,
    withCredentials: false
  }) {
    this.instance = axios.create(options);
    this.instance.defaults.headers.post['Content-type'] = 'application/json';

    this.instance.interceptors.request.use((config) => {
      log('interceptors request', config);
      if (process.env.ENV === 'DEV') {
        config.url = `${config.url}.json`;
        config.method = 'get';
      }
      return config;
    }, (error) => Promise.reject(error))
    
    this.instance.interceptors.response.use((response) => {
      log('interceptors response', response.data);
      return response.data;
    }, (error) => {
      log('interceptors error', error.message);
      return Promise.reject(this.handleErr(error));
    });
  }
  request (options) {
    return this.request(options);
  }
  post (url, params) {
    return this.instance.post(url, params);
  }
  get (url, params) {
    return this.instance.get(url, params);
  };
  all () {
    const args = Array.prototype.slice.call(arguments);
    const promiseList = args.map((item) => item.apply());
    // .then(axios.spread(function(res1, res2){
    return this.instance.all(promiseList);
  }
  handleErr (err) {
    const regex = /[\s]\d{3}/g;
    const code = err.message.match(regex)[0].replace(/\s/, '');
    const message = constant.HTTP.ERR_CODE[code];
    if (message) {
      err.message = message;
      return message;
    }
    return err.message;
  }
}

export default new Request();

export async function tryCatch(callback) {
  let result = [null, null];
  try {
    result = [await callback, null];
  } catch (e) {
    result = [null, e];
  }
  return result;
}